package jsyf.oa.service.system;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.dao.BaseJdbcDao;
import jsyf.oa.dao.system.*;
import jsyf.oa.entity.system.User2RoleEntity;
import jsyf.oa.facade.system.User2RoleFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class User2RoleService implements User2RoleFacade {


    //人员职位dao
    @Autowired
    private User2RoleDao dao;

    @Autowired
    private DepartDao departDao;
    @Autowired
    private CompanyDao companyDao;

    @Autowired
    private RoleDao roleDao;

    @Override
    public Boolean config(String userId, String roleIds) {
        dao.removeByCondition(" AND USER_ID = ? ", new String[]{userId});
        if (!StringUtils.isEmpty(roleIds)) {
            List<String> list = BaseJdbcDao.stringToList(roleIds);
            for (int i = 0; i < list.size(); i++) {
                User2RoleEntity entity = new User2RoleEntity();
                entity.setUserId(userId);
                entity.setRoleId(list.get(i));
                dao.add(entity);
            }
        }
        return true;
    }

    @Override
    public List<JSONObject> getRolesByUserId(String jsonData) {
        User2RoleEntity userRoleEntity = JSON.toJavaObject(JSON.parseObject(jsonData), User2RoleEntity.class);
        String userId = userRoleEntity.getUserId();
        List<JSONObject> roleList = new ArrayList<>();
        List<JSONObject> roles = roleDao.getViewJSONListByCondition(" AND id IN(SELECT ROLE_ID FROM T_SYS_USER_2_ROLE WHERE USER_ID = ?)", new Object[]{userId});
        if (roles != null && roles.size() > 0) {
            for (int i = 0; i < roles.size(); i++) {
                JSONObject departs = roles.get(i);
                String departId = departs.getString("departId");
               JSONObject depart= departDao.getJSONById(departId);
                String departName = depart.getString("name");
                String companyName = companyDao.getJSONById(depart.getString("companyId")).getString("name");
                departs.put("departName", departName);
                departs.put("companyName", companyName);
                roleList.add(departs);
            }
        }
        return roleList;
        /*String condition = " AND id IN(SELECT ROLE_NAME_ID FROM T_SYS_ROLE WHERE ID IN (" +
                "SELECT ROLE_ID FROM T_SYS_USER_2_ROLE T_SYS_USER_2_ROLE WHERE USER_ID=?))";
        String[] params = {userId};
        return roleNameDao.getJSONListByCondition(condition, params);*/
    }


}
